#include "Timer.h"


Timer::Timer() = default;

Timer::~Timer() {
    std::unique_lock<std::mutex> lock(mutex);
    while (!this->clients.empty()) {
        this->clients.pop();
    }
}

void Timer::add(int fd, std::chrono::milliseconds interval, const EventHandler &callback) {
    std::unique_lock<std::mutex> lock(mutex);
    Client temp(std::chrono::steady_clock::now() + interval, callback);
    this->clients.emplace(temp);
    this->fd_to_client.emplace(fd, temp);
}


void Timer::update(int fd, std::chrono::milliseconds interval) {
    std::unique_lock<std::mutex> lock(mutex);
    if (this->fd_to_client.count(fd) > 0) {
        this->fd_to_client.at(fd).expire = std::chrono::steady_clock::now() + interval;
    }

}

void Timer::clean_inactive_connection() {
    using namespace std::literals::chrono_literals;
    while (true) {
        std::unique_lock<std::mutex> lock(mutex);
        auto now = std::chrono::steady_clock::now();
        while (!this->clients.empty() && clients.top().expire <= now) {
            auto handler = clients.top().callback;
            clients.pop();
            handler();
        }
        lock.unlock();
        std::this_thread::sleep_for(5s);
    }
}

